tree.io.ajax = {}

tree.io.ajax.DATA_FORMAT = 
{
    plain: 0,
    json: 1,
    xml: 2,
    html: 3,
    csv: 4,
}

tree.io.ajax.REQUEST_METHODS = 
{
    GET: 0,
    POST: 1
}

tree.io.ajax.xhr = (url, args) ->
    ###

    get data by ajax

    the url must be in the same domain

    args:

        async: bool
        
        method: tree.io.ajax.REQUEST_METHODS.(GET|POST)
        
        complete: function(data){}
        this parameter is only used if you have an async request
        
        type: tree.io.ajax.DATA_FORMAT
        
        data: 
        {
            a: 5,
            b: 6,
        }
        
        raw_data: string

    ###
    http = new XMLHttpRequest()
    request_type = tree.io.ajax.REQUEST_METHODS.GET
    async = false
    type = tree.io.ajax.DATA_FORMAT.plain
    complete = (data) ->
        
    if  args.method?
        request_type = args.method
    
    if args.async?
        async = args.async;
    
    if args.complete?
        if not async    
            throw 'complete only for async calls'
        complete = args.complete

    if args.type?
        type = args.type;
    
    request_type_string = ''
    if args.request_type == tree.io.ajax.REQUEST_METHODS.GET
        request_type_string = 'GET'
    
    else
        request_type_string = 'POST'
    
    http.open request_type_string, url, async
    
    if type == tree.io.ajax.DATA_FORMAT.plain
        http.setRequestHeader 'Content-Type', 'text/plain'
    
    else if type == tree.io.ajax.DATA_FORMAT.xml
        http.setRequestHeader 'Content-Type', 'text/xml'
    
    else if type == tree.io.ajax.DATA_FORMAT.json
        http.setRequestHeader 'Content-Type', 'application/json'
    
    if async
        http.onreadystatechange = do (evt) ->
            if http.status == 4
                if type == tree.io.ajax.DATA_FORMAT.plain
                    complete http.responseText 
                
    formdata = null
    if args.data?
        formdata = new FormData()
        for key, value of args.data
            value = params[key]
            formdata.append key, value
        
    else if args.raw_data?
        formdata = args.raw_data;
    
    http.send formdata
    if not async
        if type == tree.io.ajax.DATA_FORMAT.plain
            return http.responseText
        
        else if type == tree.io.ajax.DATA_FORMAT.xml
            return http.responseXML
        
        else if type == tree.io.ajax.DATA_FORMAT.html
            return ''
            
        else
            return http.responseText

